<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import Cookies from 'js-cookie'
import store from '@/store'
import { loginOnWeb } from '@/api'

const router = useRouter()

const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: false,
  role: 'user' // 设置默认角色为普通用户
})

const loading = ref(false)
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度必须在3到20个字符之间', trigger: 'blur' }
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  role: [{ required: true, message: '请选择用户角色', trigger: 'change' }]
}

const loginFormRef = ref(null)

const goToRegister = () => {
  router.push('/register')
}

// 模拟获取用户权限的API
const fetchUserPermissions = async (username, role) => {
  // 根据角色返回不同的权限列表
  const permissionsMap = {
    admin: [
      // 简化的路径权限配置
      'user',       // 可以访问/user路径
      'admin',      // 可以访问/admin路径
      'order',      // 可以访问/order路径
      'merchant', // 可以访问/statistics路径
      'search',
      'orders',
      'favorites',
      'recently-viewed'
    ],
    merchant: [
      // 简化的路径权限配置
      'product',    // 可以访问/product路径
      'order',      // 可以访问/order路径
      'statistics', // 可以访问/statistics路径
      
    ],
    user: [
      // 简化的路径权限配置
      'product',    // 可以访问/product路径
      'order',      // 可以访问/order路径
      'user',       // 可以访问/user路径
      'search'
      
    ]
  }

  return permissionsMap[role] || []
}
// 登录按钮点击事件
const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      try {
        // 这里应该调用实际的登录API
        loginOnWeb(loginForm).then(response => {
          if (response.data.state == 1) {
            const userInfo = response.data.data
            console.log("登录成功");
            
            // 模拟登录成功
            if (loginForm.rememberMe) {
              Cookies.set('username', userInfo.username, { expires: 7 })
            } else {
              Cookies.remove('username')
            }

            // 获取用户权限
            fetchUserPermissions(userInfo.username, userInfo.role)
              .then(permissions => {
                
                // 存储用户信息和权限到store
                store.setUser({
                  username: loginForm.username,
                  role: loginForm.role
                })
                store.setRole(loginForm.role)
                store.setPermissions(permissions)
                store.setStore("token",userInfo.token)
                console.log('用户权限:', permissions)
                ElMessage.success('登录成功')
                // 根据角色跳转到不同页面
                switch(loginForm.role) {
                  case 'admin':
                    router.push('/admin')
                    break
                  case 'merchant':
                    router.push('/merchant')
                    break
                  default:
                    router.push('/user')
                }
              })
          }else{
            console.log("登录失败");
            ElMessage.error('登录失败:'+response.data.data)
          }
        })
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error('登录失败，请检查用户名和密码')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <img src="@/assets/logo.svg" alt="Logo" class="logo" />
        <h2>MyFootballShow</h2>
        <p>球鞋爱好者的购物天堂</p>
      </div>

      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="用户名" prefix-icon="User" size="large" />
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="密码" prefix-icon="Lock" size="large"
            show-password />
        </el-form-item>

        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="loginForm.role">
            <el-radio label="user">普通用户</el-radio>
            <el-radio label="merchant">商家</el-radio>
            <el-radio label="admin">管理员</el-radio>
          </el-radio-group>
        </el-form-item>

        <div class="remember-box">
          <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
          <!-- <el-link type="primary" :underline="true">忘记密码?</el-link> -->
        </div>

        <el-button type="primary" :loading="loading" class="login-button" @click="handleLogin" size="large">
          登录
        </el-button>

        <div class="register-link">
          <span>还没有账号?</span>
          <el-link type="primary" :underline="false" @click="goToRegister">立即注册</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

/* PC端适配样式 */
@media (min-width: 1024px) {
  .login-box {
    width: 500px;
    padding: 60px;
  }

  .login-header h2 {
    font-size: 32px;
  }

  .login-header p {
    font-size: 16px;
  }
}

.login-box {
  width: 450px;
  padding: 50px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo {
  width: 100px;
  height: 100px;
  margin-bottom: 20px;
}

.login-header h2 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.login-header p {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.login-form {
  margin-top: 20px;
}

.remember-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.login-button {
  width: 100%;
  margin-bottom: 20px;
  border-radius: 4px;
  height: 48px;
  font-size: 16px;
}

.register-link {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.register-link span {
  margin-right: 5px;
}
</style>